package com.proxy.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.proxy.daijia.customer.mapper.CustomerInfoMapper;
import com.proxy.daijia.customer.mapper.CustomerLoginLogMapper;
import com.proxy.daijia.customer.service.CustomerInfoService;
import com.proxy.daijia.model.entity.customer.CustomerInfo;
import com.proxy.daijia.model.entity.customer.CustomerLoginLog;
import com.proxy.daijia.model.vo.customer.CustomerInfoVo;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private CustomerLoginLogMapper customerLoginLogMapper;

    @Override
    public Long login(String code) {
        String openId = null;
        try {
            // 获取微信小程序的openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
        //判断是否第一次登录
        CustomerInfo customerInfo = getOne(Wrappers.<CustomerInfo>lambdaQuery().eq(CustomerInfo::getWxOpenId, openId));
        if (customerInfo == null) {
            //保存用户信息
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openId);
            save(customerInfo);
        }

        //登录日志
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);
        return customerInfo.getId();
    }

    //获取登录信息
    @Override
    public CustomerInfoVo getCustomerInfoVo(Long customerId) {
        CustomerInfo customerInfo = getById(customerId);
        CustomerInfoVo customerInfoVo = new CustomerInfoVo();
        BeanUtils.copyProperties(customerInfo, customerInfoVo);
        boolean isBindPhone = StringUtils.isNotBlank(customerInfo.getPhone());
        customerInfoVo.setIsBindPhone(isBindPhone);
        return customerInfoVo;
    }
}
